package com.gzj.environment.module.log.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzj.environment.enums.code.impl.commonCode.ResultCode;
import com.gzj.environment.framework.exception.CustomerException;
import com.gzj.environment.framework.util.DateUtil;
import com.gzj.environment.model.log.criteria.LogCriteria;
import com.gzj.environment.model.log.entity.Log;
import com.gzj.environment.module.log.mapper.LogMapper;
import com.gzj.environment.module.log.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: tsing
 * @create: 2021-01-22 19:16
 */
@Service
public class LogServiceImpl implements LogService {

    @Autowired
    private LogMapper logMapper;

    @Override
    public void writeLog(Log log) {
        logMapper.insert(log);
    }

    /**
     * 分页条件查询
     *
     * @param criteria 条件查询对象
     * @return
     */
    @Override
    public Page<Log> page(LogCriteria criteria) {
        // 1.封装查询对象
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(criteria.getKeyword())) {
            wrapper.and(item ->
                    item.like("log_method", criteria.getKeyword())
                            .or().like("log_content", criteria.getKeyword())
                            .or().like("error_msg", criteria.getKeyword()));
        }
        if (StrUtil.isNotBlank(criteria.getIp())) {
            wrapper.like("ip", criteria.getIp());
        }
        if (ObjectUtil.isNotNull(criteria.getStartTime()) && ObjectUtil.isNotNull(criteria.getEndTime())) {
            wrapper.ge("create_time", criteria.getStartTime());
            wrapper.le("create_time", criteria.getEndTime());
        } else if (ObjectUtil.isNotNull(criteria.getStartTime())) {
            wrapper.ge("create_time", criteria.getStartTime());
            wrapper.le("create_time", DateUtil.LATEST_DATE);
        } else if (ObjectUtil.isNotNull(criteria.getEndTime())) {
            wrapper.ge("create_time", DateUtil.EARLIEST_DATE);
            wrapper.le("create_time", criteria.getEndTime());
        }
        // 2.进行查询
        Page<Log> pageInfo = new Page<>(criteria.getPage(), criteria.getSize());
        logMapper.selectPage(pageInfo, wrapper);
        // 3.结果处理
        if (pageInfo.getTotal() == 0) {
            throw new CustomerException(ResultCode.RETURN_DATA_NOT_FOUND);
        }
        return pageInfo;
    }
}
